// pages/teacher/todo/todo.js
Page({
  data: {
    todoList: [],
    loading: true,
    currentTab: 0,
    tabs: ['全部', '待处理', '已处理']
  },

  onLoad: function() {
    this.fetchTodoList();
  },
  
  onShow: function() {
    // 每次页面显示时刷新待办列表
    this.fetchTodoList();
  },
  
  // 获取待办列表
  // 修改 fetchTodoList 函数，确保正确处理返回的数据
  fetchTodoList: function() {
    this.setData({
      loading: true
    });
    
    wx.request({
      url: 'http://localhost:3000/api/teacher/todos',
      method: 'GET',
      header: {
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        console.log('获取待办事项数据:', res.data);
        
        if (res.statusCode === 200 && res.data.success) {
          // 确保正确获取数据数组
          const todoList = res.data.data || [];
          
          // 根据当前选中的标签过滤数据
          let filteredList = todoList;
          if (this.data.currentTab === 1) { // 待处理
            filteredList = todoList.filter(item => 
              item.status === 'pending' || !item.status || 
              (item.type === 'grade' && item.details && item.details.progress < 100)
            );
          } else if (this.data.currentTab === 2) { // 已处理
            filteredList = todoList.filter(item => 
              item.status === 'completed' || 
              (item.type === 'grade' && item.details && item.details.progress === 100)
            );
          }
          
          this.setData({
            todoList: filteredList,
            loading: false
          });
        } else {
          this.setData({
            todoList: [],
            loading: false
          });
          
          wx.showToast({
            title: res.data.message || '获取待办事项失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取待办事项失败:', err);
        this.setData({
          loading: false,
          todoList: []
        });
        
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },
  
  // 切换标签
  switchTab: function(e) {
    const tabIndex = e.currentTarget.dataset.index;
    this.setData({
      currentTab: tabIndex
    });
  },
  
  // 标记待办为已完成
  markAsCompleted: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.request({
      url: `http://localhost:3000/api/teacher/todos/${id}/complete`,
      method: 'PUT',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 更新本地待办状态
          const todoList = this.data.todoList;
          const index = todoList.findIndex(item => item.id === id);
          
          if (index !== -1) {
            todoList[index].isCompleted = true;
            this.setData({
              todoList: todoList
            });
            
            wx.showToast({
              title: '已标记为完成',
              icon: 'success'
            });
          }
        }
      },
      fail: () => {
        // 模拟成功
        const todoList = this.data.todoList;
        const index = todoList.findIndex(item => item.id === id);
        
        if (index !== -1) {
          todoList[index].isCompleted = true;
          this.setData({
            todoList: todoList
          });
          
          wx.showToast({
            title: '已标记为完成',
            icon: 'success'
          });
        }
      }
    });
  },
  
  // 查看待办详情
  viewTodoDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    const todo = this.data.todoList.find(item => item.id === id);
    
    if (todo) {
      // 根据待办类型跳转到不同页面
      if (todo.type === 'grade') {
        wx.navigateTo({
          url: '/pages/teacher/chengji/chengji'
        });
      } else if (todo.type === 'schedule') {
        wx.navigateTo({
          url: '/pages/teacher/kechenbiao/kechenbiao'
        });
      } else if (todo.type === 'meeting') {
        wx.navigateTo({
          url: '/pages/teacher/xiaoxi/detail/detail?id=' + id
        });
      } else {
        wx.navigateTo({
          url: '/pages/teacher/xiaoxi/detail/detail?id=' + id
        });
      }
    }
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.fetchTodoList();
    wx.stopPullDownRefresh();
  },
  
  // 修改处理待办事项的函数
  handleTodoItem: function(e) {
    const todoId = e.currentTarget.dataset.id;
    const todoType = e.currentTarget.dataset.type;
    
    console.log('处理待办事项:', todoId, todoType);
    
    // 根据不同类型的待办事项进行不同的处理
    if (todoType === 'leave') {
      // 请假申请处理
      wx.navigateTo({
        url: `/pages/teacher/qingjia/detail/detail?id=${todoId.split('_')[1]}`
      });
    } else if (todoType === 'attendance') {
      // 考勤处理
      wx.navigateTo({
        url: `/pages/teacher/kaoqin/detail/detail?id=${todoId.split('_')[1]}`
      });
    } else if (todoType === 'grade') {
      // 成绩录入处理
      wx.navigateTo({
        url: `/pages/teacher/chengjiluru/chengjiluru?id=${todoId.split('_')[1]}`
      });
    }
  }
});